/*
 * Copyright (C) 2013 47 Degrees, LLC
 *  http://47deg.com
 *  hello@47deg.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.pricy.me;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.atermenji.android.iconictextview.IconicFontDrawable;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.pricy.me.StreamProductsActivity.ListAppTask;
import com.pricy.me.adapters.ProductAdapter;
import com.pricy.me.model.CategoryIcon;
import com.pricy.me.model.Notification;
import com.pricy.me.model.Product;
import com.pricy.me.model.ProductExtended;

public class DiscoverActivity extends ActionItems {
	
    private static final int REQUEST_CODE_SETTINGS = 0;
    private ProductAdapter adapter;
    private List<ProductExtended> data;
    private int current = 0;
    private ListView swipeListView;
    private Button btnLoadMore;
    private ProgressDialog progressDialog;
    private Handler btnHandler;
	private int category;
	/**
	 * Variable pour gerer le traitement des erreur 
	 */
	private Handler noDataHandler ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Theme_Sherlock_Light);
        setContentView(R.layout.product_list_view);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        Intent intent = getIntent();
        CategoryIcon c = new CategoryIcon(0);
		final List<CategoryIcon> dataCat = c.getAll(this);
		int item = intent.getIntExtra(DiscoverActivity.this.getString(R.string.category), 1);
        category = dataCat.get(item).getId();
        
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
		        .cacheOnDisc()
		        .build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
		        .defaultDisplayImageOptions(defaultOptions)
		        .build();
		ImageLoader.getInstance().init(config);

        data = new ArrayList<ProductExtended>();

        adapter = new ProductAdapter(this, data);

        swipeListView = (ListView) findViewById(R.id.example_lv_list);
        
        View header = View.inflate(this, R.layout.discover_header, null);
        ImageView hIcon = (ImageView) header.findViewById(R.id.catheader_icon);
        TextView hTitle = (TextView) header.findViewById(R.id.catheader_title);
        ImageView hIconUser = (ImageView) header.findViewById(R.id.catheader_userphoto);
        TextView hUserTitle = (TextView) header.findViewById(R.id.catheader_userphoto_title);
        hTitle.setText(dataCat.get(item).getTitle());
        hUserTitle.setText("Ambassadeur");
        final IconicFontDrawable iconicFontDrawable = new IconicFontDrawable(this);
        iconicFontDrawable.setIcon(dataCat.get(item).getIcon());
        hIcon.setBackgroundDrawable(iconicFontDrawable);
        swipeListView.addHeaderView(header);
        
        
        // LoadMore button
        btnLoadMore = new Button(this);
        btnLoadMore.setText(DiscoverActivity.this.getString(R.string.idontWant));
        // Adding Load More button to lisview at bottom
       // swipeListView.addFooterView(btnLoadMore);
        btnLoadMore.setVisibility(View.GONE);
        
        btnLoadMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new ListAppTask().execute();
			}
		});
        
        
        SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
        swingBottomInAnimationAdapter.setAbsListView(swipeListView);
        swipeListView.setAdapter(swingBottomInAnimationAdapter);
        

        
        reload();

        new ListAppTask().execute();

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
        
        btnHandler = new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		btnLoadMore.setVisibility(View.GONE);
        	}
        };
        //Traitement du message d'errerur
       noDataHandler=  new Handler(){
       	@Override
       	public void handleMessage(Message msg) {
       		TextView v = new TextView(DiscoverActivity.this);
       		 v.setText(DiscoverActivity.this.getString(R.string.errorCat));
       		swipeListView.addFooterView(v);	
       	}
       };
        
        
    }

    private void reload() {
//        swipeListView.setSwipeMode(SwipeListView.SWIPE_MODE_RIGHT);
//        swipeListView.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_DISMISS);
//        swipeListView.setSwipeActionRight(SwipeListView.SWIPE_ACTION_REVEAL);
    }

    public int convertDpToPixel(float dp){
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi/160f);
        return (int) px;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTINGS:
                reload();
               break;
        }
    }

    public class ListAppTask extends AsyncTask<Void, Void, List<ProductExtended>> {

		protected List<ProductExtended> doInBackground(Void... args) {
        	Product product = new Product();
        	List<ProductExtended> products;
        		products = product.getDiscoverProducts(current,category,getApplicationContext());
        	if(!products.isEmpty()) 
        		current += 5 ;
        	else btnHandler.sendEmptyMessage(0);
        	/*Cette section nous permet d'afficher des messages d'erreur
        	 * Lorsqu'il y'aura manque de donn�e dans la Bd ou bien une perte
        	 * de connexion
        	 * */
        	if(products.size()==0){	 
        		noDataHandler.sendEmptyMessage(0);
        	}
        	return products;
        }

        protected void onPostExecute(List<ProductExtended> result) {
        	try {
        		data.addAll(result);
                adapter.notifyDataSetChanged();
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                    btnLoadMore.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                // nothing
            }
            
        }
    }

    public String readFile(String file, Context c) {
		StringBuilder json = new StringBuilder();
		try {
			FileInputStream fis = c.openFileInput(file);
			BufferedReader r = new BufferedReader(new InputStreamReader(fis));
			String line;
			while ((line = r.readLine()) != null) {
			    json.append(line);
			}
			fis.close();
			return json.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

	@Override
	void actualiser() {
		current = 0;
		data = new ArrayList<ProductExtended>();
		progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
		new ListAppTask().execute();
		
	}

	@Override
	int whereami() {
		return DISCOVER_ACTIVITY;
	}
}
